var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , ejs = require('ejs');
var fork = require('child_process').fork;
var logger = require('./service/Logger');
var staticExpires = require('./service/staticExpires');
var config = require('./config').config;
var LimitStackMap = require('./lib/LimitStackMap');
var redisManager = require('./proxy/redisManager');
var WechatAPI = require('wechat-api');
var cronJob = require('cron').CronJob;

/*
                    _ooOoo_
                   o8888888o
                   88" . "88
                   (| -_- |)
                   O\  =  /O
                ____/`---'\____
              .'  \\|     |//  `.
             /  \\|||  :  |||//  \
            /  _||||| -:- |||||-  \
            |   | \\\  -  /// |   |
            | \_|  ''\---/''  |   |
            \  .-\__  `-`  ___/-. /
          ___`. .'  /--.--\  `. . __
       ."" '<  `.___\_<|>_/___.'  >'"".
      | | :  `- \`.;`\ _ /`;.`/ - ` : | |
      \  \ `-.   \_ __\ /__ _/   .-` /  /
 ======`-.____`-.___\_____/___.-`____.-'======
                    `=---='
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
              佛祖保佑       永无BUG
 */
limitStackMap = new LimitStackMap(100);
relationBuilder = {};

var app = express();
    // 服务核心配置
	app.set('port', 8000);
	app.set('views', __dirname + '/views');
	app.engine('.html', ejs.__express);
	app.set('view engine', 'html');
    app.use(express.logger('dev'));
    app.use(express.compress());
	app.use(express.bodyParser());
	app.use(express.cookieParser());
	app.use(express.session({ secret : 'fj_session', cookie:{maxAge:6000000}}));//session过期时间1小时
    app.use(staticExpires.setCacheExpires());
	app.use(express.static(__dirname + '/static/js'));
	app.use(express.static(__dirname + '/static/css'));
	app.use(express.static(__dirname + '/static/img/bg'));
    app.use(express.static(__dirname + '/static/img'));
    app.use(function(req, res, next){
        res.locals.static_js_path = config.production_js_path
        next();
    });
    routes(app);

var server = http.createServer(app);
    server.listen(app.get('port'), function(){
        logger.debug("fanju wechat service start!");
        //wechatAccessToken.getWechatAccToken(function(token){});
    });
exports.start = function(){
    server.listen(app.get('port'), function(){
        logger.debug("fanju wechat service start!");
        //wechatAccessToken.getWechatAccToken(function(token){});
    });
    startRelationBuidder();
    updateJsapiTicket();
    jsapiTicketTimer();
}

function jsapiTicketTimer(){
    var ticketJob = new cronJob({
        cronTime: '0 0 */1 * * *',
        onTick: function() {
            updateJsapiTicket();
        },
        onComplete: function(){
            logger.debug('tokenJob stop...');
        },
        start: true
    });
    ticketJob.start();
}

function updateJsapiTicket(){
    redisManager.getAccesstoken(function(err, token){
        WechatAPI.requestJsapiTicket(token, function(err, ticket){
            console.log(ticket)
            limitStackMap['jsapi_ticket'] = ticket
        })
    })
}

function startRelationBuidder(){
    //关系维护进程
    relationBuilder = fork('./relationBuilder.js');
    relationBuilder.on('message', function(data){
        console.log(data);
    });
    relationBuilder.on('uncaughtException', function(err){
        logger.debug('关系维护出错...')
        logger.error(err);
    });
    relationBuilder.on('exit', function() {
        logger.debug('关系维护出错,退出...');
        startRelationBuidder();// 异常退出重启
    });
}